package com.beasu.tingting.ui.main

import android.app.Application
import android.preference.PreferenceManager
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import com.beasu.tingting.utils.*
import java.net.URLEncoder

class MainViewModel(val c:Application): AndroidViewModel(c) {

    val textString :MutableLiveData<String> = MutableLiveData("")
    val morseCodeString:MutableLiveData<String> = MutableLiveData("")
    val time: MutableLiveData<Int> = MutableLiveData(1000)
     var di_frequency :MutableLiveData<Int>  = MutableLiveData(1000)
     var da_frequency :MutableLiveData<Int> = MutableLiveData(50)
    lateinit var  blankWave :ShortArray
     lateinit var diWave:ShortArray
     lateinit var  daWave : ShortArray
    lateinit var smalBlankWave :ShortArray
    val wave = Wave()
    private val conUtil: ConvertByBase64 = ConvertByBase64()

    init {
        try {
            val sp = PreferenceManager.getDefaultSharedPreferences(c.applicationContext)
            di_frequency .value= sp.getString("di_frequency","1000")!!.toInt()
            da_frequency.value= sp.getString("da_frequency","1000")!!.toInt()
            time.value= sp.getString("time","50")!!.toInt()
            smalBlankWave = wave.sin(100,20)
            smalBlankWave.fill(0)
           //s calclWave()
        }catch (e:NumberFormatException ){
            e.printStackTrace()
        }
    }
    fun convertToMorseCode(){
        var s = textString.value

      //  Log.i("url",URLEncoder.encode(s,"utf-8"))

        if (s != null) {
          //  s = conUtil.convertToAscii(s)
            val buf = StringBuffer()
            for(c in s.toUpperCase()){
                    buf.append(MorseCodeTable.getValue(c))
                    buf.append("    ")
            }
            Log.i("str",buf.toString())
            morseCodeString.value =buf.toString()
        }
    }
    fun convertToText(){
        val s = morseCodeString.value
        if(s != null){

            val buf = StringBuffer()
          val strs = s.split(" ")
            for(str in strs){
                buf.append(MorseCodeTable.getKey(str))
            }
//            textString.value  = conUtil.convertToText(buf.toString())
            textString.value  =buf.toString()
        }
    }
    fun clear(){
        textString.value =""
        morseCodeString.value =""
    }
      fun  calcDiWave(){
        diWave = wave.sin(di_frequency.value!!,time.value!!)
    }
     fun calcDaWave(){
        daWave = wave.sin(da_frequency.value!!,time.value!!)
    }
    fun cakcBlankWave(){
        blankWave = ShortArray(diWave.size)
    }
}
